<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>慧择人机对话系统</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{{ url_for('static', filename='styles/style.css') }}">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>

<body>

<!-- partial:index.partial.html -->
<section class="msger">
    <header class="msger-header">
        <div class="msger-header-title">
            <i class="fas fa-bug"></i> 慧择人机对话系统<i class="fas fa-bug"></i>
        </div>
    </header>

    <main class="msger-chat">


    </main>

    <form class="msger-inputarea">
        <textarea type="text" class="msger-input" id="textInput" placeholder="用户回复"></textarea>
        <textarea type="text" class="msger-info" id="infoInput" placeholder="用户信息">{}</textarea>
        <button type="submit" class="msger-send-btn">Send</button>
    </form>
</section>
<!-- partial:prompt.partial.html -->
<!--?<section class="msger">-->
<!--?    <header class="msger-header">-->
<!--?        <div class="msger-header-title">-->
<!--?            <i class="fas fa-bug"></i> 用户问题<i class="fas fa-bug"></i>-->
<!--?        </div>-->
<!--?    </header>-->

<!--?    <main class="msger-question">-->


<!--?    </main>-->
<!--?</section>-->
<!-- partial:prompt.partial.html -->
<section class="msger">
    <header class="msger-header">
        <div class="msger-header-title">
            <i class="fas fa-bug"></i> 用户问题prompt<i class="fas fa-bug"></i>
        </div>
    </header>

    <main class="msger-skill">


    </main>
</section>
<!-- partial:prompt.partial.html -->
<section class="msger">
    <header class="msger-header">
        <div class="msger-header-title">
            <i class="fas fa-bug"></i> 销售技巧prompt<i class="fas fa-bug"></i>
        </div>
    </header>

    <main class="msger-situation">


    </main>
</section>
<!-- partial:prompt.partial.html -->
<section class="msger">
    <header class="msger-header">
        <div class="msger-header-title">
            <i class="fas fa-bug"></i> 话术生成prompt<i class="fas fa-bug"></i>
        </div>
    </header>

    <main class="msger-conversation">


    </main>
</section>
<!-- partial -->
<script src='https://use.fontawesome.com/releases/v5.0.13/js/all.js'></script>
<script>

    const msgerForm = get(".msger-inputarea");
    const msgerInput = get(".msger-input");
    const msgerInfo = get(".msger-info");
    const msgerChat = get(".msger-chat");
    const msgerQuestion = get(".msger-question");
    const msgerSkill = get(".msger-skill");
    const msgerSituation = get(".msger-situation");
    const msgerConversation = get(".msger-conversation");
    const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';


    // Icons made by Freepik from www.flaticon.com
    const BOT_IMG = "https://image.flaticon.com/icons/svg/327/327779.svg";
    const PERSON_IMG = "https://image.flaticon.com/icons/svg/145/145867.svg";
    const BOT_NAME = "SalesBot";
    const PERSON_NAME = "You";

    /**
     * 随机生成索引
     * @param min 最小值
     * @param max 最大值
     * @param i 当前获取位置
     */
    function RandomIndex(min, max, i) {
        let index = Math.floor(Math.random() * (max - min + 1) + min),
                numStart = _charStr.length - 10;
        //如果字符串第一位是数字，则递归重新获取
        if (i == 0 && index >= numStart) {
            index = RandomIndex(min, max, i);
        }
        //返回最终索引值
        return index;
    }

    function getRandomString(len) {
        let min = 0, max = _charStr.length - 1, _str = '';
        //判断是否指定长度，否则默认长度为15
        len = len || 15;
        //循环生成字符串
        for (var i = 0, index; i < len; i++) {
            index = RandomIndex(min, max, i);
            _str += _charStr[index];
        }
        return _str;
    }

    const userId = getRandomString(20)

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    //获取url中的scene参数,如果没有则默认为norm
    var initScene = getUrlParam("initScene");
    if (initScene == null) {
        initScene = "norm";
    }
    //页面初始化时，根据url传入的initScene参数，获取机器人的欢迎语
    $(document).ready(function () {
        $.get("/init", {initScene: initScene, userId: userId}).done(function (data) {
            console.log(data);
            const msgText = data;
            appendMessage(BOT_NAME, BOT_IMG, "left", msgText);
        });
    });


    // 页面增加个按钮，点击后，页面跳转到另一个场景
    var btn = document.createElement("button");
    btn.innerHTML = "保险";
    btn.onclick = function () {
        window.location.href = "/?initScene=insurance";
    };
    document.body.appendChild(btn);

    var btn = document.createElement("button");
    btn.innerHTML = "借贷";
    btn.onclick = function () {
        window.location.href = "/?initScene=credit";
    };
    document.body.appendChild(btn);


    // 按回车触发消息发送
    msgerInput.addEventListener("keypress", event => {
        if (event.keyCode == 13 && event.shiftKey == false) {
            event.preventDefault();
            msgerForm.dispatchEvent(new Event("submit"));
        }
    });


    msgerForm.addEventListener("submit", event => {
        event.preventDefault();

        const msgText = msgerInput.value;
        const msgInfo = msgerInfo.value;
        if (!msgText) return;

        appendMessage(PERSON_NAME, PERSON_IMG, "right", msgText);
        msgerInput.value = "";
        botResponse(msgText, msgInfo);
    });

    function appendMessage(name, img, side, text) {
        //   Simple solution for small apps
        const msgHTML = `
<div class="msg ${side}-msg">
  <div class="msg-img" style="background-image: url(${img})"></div>
  <div class="msg-bubble">
    <div class="msg-info">
      <div class="msg-info-name">${name}</div>
      <div class="msg-info-time">${formatDate(new Date())}</div>
    </div>
    <div class="msg-text">${text}</div>
  </div>
</div>
`;

        msgerChat.insertAdjacentHTML("beforeend", msgHTML);
        msgerChat.scrollTop += 500;
    }



    function appendSkill(name, img, side, text) {
        //   Simple solution for small apps
        const msgHTML = `
<div class="msg ${side}-msg">
  <div class="msg-img" style="background-image: url(${img})"></div>
  <div class="msg-bubble">
    <div class="msg-info">
      <div class="msg-info-name">${name}</div>
      <div class="msg-info-time">${formatDate(new Date())}</div>
    </div>
    <div class="msg-text">${text}</div>
  </div>
</div>
`;

        msgerSkill.insertAdjacentHTML("beforeend", msgHTML);
        msgerSkill.scrollTop += 500;
    }

    function appendSituation(name, img, side, text) {
        //   Simple solution for small apps
        const msgHTML = `
<div class="msg ${side}-msg">
  <div class="msg-img" style="background-image: url(${img})"></div>
  <div class="msg-bubble">
    <div class="msg-info">
      <div class="msg-info-name">${name}</div>
      <div class="msg-info-time">${formatDate(new Date())}</div>
    </div>
    <div class="msg-text">${text}</div>
  </div>
</div>
`;

        msgerSituation.insertAdjacentHTML("beforeend", msgHTML);
        msgerSituation.scrollTop += 500;
    }

    function appendConversation(name, img, side, text) {
        //   Simple solution for small apps
        const msgHTML = `
<div class="msg ${side}-msg">
  <div class="msg-img" style="background-image: url(${img})"></div>
  <div class="msg-bubble">
    <div class="msg-info">
      <div class="msg-info-name">${name}</div>
      <div class="msg-info-time">${formatDate(new Date())}</div>
    </div>
    <div class="msg-text">${text}</div>
  </div>
</div>
`;

        msgerConversation.insertAdjacentHTML("beforeend", msgHTML);
        msgerConversation.scrollTop += 500;
    }

    function botResponse(rawText, rawInfo) {

        // Bot Response
        $.get("/message", {message: rawText, userId: userId, userInfo: rawInfo}).done(function (data) {
            console.log(rawText);
            console.log(data);

            // 解析JSON字符串为JavaScript对象
            const responseData = JSON.parse(data);

            // 提取需要的信息
            const sessionId = responseData.sessionId
            const userQuestion = responseData.user_question
            const userQuestionPrompt = responseData.knowledge_solution_set
            const salesSkill = responseData.wechat_skill_utter_set
            const salesSkillPrompt = responseData.wechat_skill
            const wechatSkillUtter = responseData.wechat_skill_utter
            const userSituationPrompt = responseData.user_situation_prompt
            const msgText = responseData.context;
            const msgNo = responseData.wav_no;
            const conversationPrompt = responseData.conversation_prompt
            appendMessage(BOT_NAME, BOT_IMG, "left", sessionId + '<br>' + msgText);
            // appendQuestion(BOT_NAME, BOT_IMG, "left",'<br>' + userQuestion);
            appendSkill(BOT_NAME, BOT_IMG, "left", userQuestionPrompt + '<br>' + userQuestion);
            appendSituation(BOT_NAME, BOT_IMG, "left", salesSkill + '<br>' + wechatSkillUtter);
            appendConversation(BOT_NAME, BOT_IMG, "left", salesSkillPrompt);
        });

    }


    // Utils
    function get(selector, root = document) {
        return root.querySelector(selector);
    }

    function formatDate(date) {
        const h = "0" + date.getHours();
        const m = "0" + date.getMinutes();
        const s = "0" + date.getSeconds();

        return `${h.slice(-2)}:${m.slice(-2)}:${s.slice(-2)}`;
    }


</script>

</body>

</html>